package com.ykt.mall.ctrl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.ykt.interceptor.Seach;
import com.ykt.mall.pageModel.TreeNode;
import com.ykt.model.ProductImg;
import com.ykt.model.Shop;
import com.ykt.model.User;

@ControllerBind(controllerKey="/shop")
public class ShopCtrl extends AdminBaseCtrl<Shop>{
	public ShopCtrl(){
		super(Shop.class);
	}
	
	@Override
	public void edit() {
		// TODO Auto-generated method stub
		super.edit();
		User u = getCurrentUser();
		setAttr("current_user", u);
	}

	@Before(Tx.class)
	public void save(){
		Shop shop=Shop.dao.findShopByName(getPara("shop.name"));
		if(shop!=null && shop.getInt("id") !=  getParaToInt("shop.id") ){
				rendJson_(false, "商户名称已存在！");
		}
		else{
			super.save();
		}
	}
	/**
	 * 下拉列表多选
	 */
	public void combotree() {

		String sql="select id,name from shop";
		if(isParaExists(0)){		
			//不选自己
			sql+=" where id <> "+getPara();
		}
		
		List<Record> dataList = Db.find(sql);
		List<TreeNode> list = new ArrayList<TreeNode>();
		for(Record r : dataList ){
			TreeNode rootNode = new TreeNode();
			rootNode.setId(r.getInt("id"));
			rootNode.setText(r.getStr("name"));
			rootNode.setIconCls("icon-home");
			rootNode.setCanChk(false);
			list.add(rootNode);
		}
		this.renderJson_(list);
	}
	
	protected void otherSeach(Seach seach) {
		if(getCurrentUser().getInt("id")!=1){
			String shopids=getCurrentShopIds();
			seach.setSqlWhere( seach.getSqlWhere()+" and id in ("+shopids+")");
			seach.setOrderBy(" order by id desc ");
		}
	}
	
	@Override
	
	protected void otherSave(Model<Shop> m) {
		if(getCurrentUser().getInt("id")!=1){
			//如果不是管理员添加的商户 自动设置为当前登录商户的子商户
			Integer pid= getCurrentUser().get("shop_id");
			Integer sid = m.getInt("id");
			//查询是否存在这个子商户 如果不存在就自动添加
			List<Record> list = Db.find("select * from shop_relation where pid=? and sid =?", pid,sid);
			if(list.isEmpty()){
				Shop p_shop =Shop.dao.findById(pid);
				String sids = p_shop.get("sids");
				Db.update("insert into shop_relation(pid,sid,create_time) values(?,?,now())",pid,sid);
				sids+=(","+sid);
				if(sids.indexOf(",")==0)
					sids = sids.substring(1);
				p_shop.set("sids", sids).update();//子ID字符串
			}
			return;
		}
		Integer shop_id = m.getInt("id");
		String []sidList=getParaValues("sids");
		String sids="";// 子商户ID串
		boolean hasSub=false;//是否有子商户
		Db.update("delete from shop_relation where pid=?",shop_id);//先删除所有权限
		if(sidList!=null){
			for(String id_str : sidList) {
				sids+=id_str+",";
				Integer sid = Integer.parseInt(id_str);
				Db.update("insert into shop_relation(pid,sid,create_time) values(?,?,now())",shop_id,sid);
			}
			if(sids.length()>1)  
			{
				sids=sids.substring(0, sids.length()-1);
				hasSub=true;
			}
		}
		
		
		
		Shop.dao.deleteAllPic(shop_id);//先删除所有
		
		String[] logos = this.getParaValues("logos");
		Date time = new Date();
		int seq=0;
		m.set("logo",null);
		m.set("has_sub",hasSub);
		m.set("sids",sids);
		if(logos!=null&&logos.length>0) {
			for(String logo : logos){
				Map<String,Object>map = new HashMap<String,Object>();
				map.put("shop_id", shop_id );
				map.put("url", logo );
				map.put("seq", seq++ );
				map.put("type",0);
				map.put("create_time", time );
				map.put("update_time", time );
				new ProductImg().setAttrs(map).save();
			}
			m.set("logo", logos[logos.length-1]);//最后一张图片设置为商品的默认图片
		}
		m.update();
	}
	public void combobox(){
		String sql="select * from shop ";
		if(getCurrentUser().getInt("id")!=1){
			String shopids=getCurrentShopIds();
			sql+=" where id in ("+shopids+")";
		}
		this.renderJson(Shop.dao.find(sql));
	}
	
}
